import { AnimalDatas } from "./GameDefine";

cc.Class({
    extends: cc.Component,

    properties: {
        sprAnimal: cc.Sprite,
        nodBubble: cc.Node,
    },

    onLoad() {
        this.oldScaleX = this.sprAnimal.node.scaleX;
        this.oldScaleY = this.sprAnimal.node.scaleY;
    },

    init(index) {
        this._index = index;
        this.sprAnimal.node.stopAllActions();
        this.sprAnimal.node.scaleX = this.oldScaleX;
        this.sprAnimal.node.scaleY = this.oldScaleY;

        let data = AnimalDatas[index];
        let url = 'textures/animals/' + data.icon;
        G.common.setSpriteFrame(this.sprAnimal, url, () => {
            this.nodBubble.width = this.sprAnimal.node.width * Math.abs(this.sprAnimal.node.scaleX) * 1.5;
            this.nodBubble.height = this.nodBubble.width;
            this.node.width = this.nodBubble.width;
            this.node.height = this.nodBubble.height;

            this.sprAnimal.node.runAction(cc.repeatForever(
                cc.sequence(
                    cc.scaleTo(0.3, 1 * this.oldScaleX, 0.9 * this.oldScaleY),
                    cc.scaleTo(0.3, 1 * this.oldScaleX, 1 * this.oldScaleY),
                    cc.scaleTo(0.3, 1 * this.oldScaleX, 1.1 * this.oldScaleY),
                    cc.scaleTo(0.3, 1 * this.oldScaleX, 1 * this.oldScaleY),
                )
            ))
        });

        this._randomMove();
    },

    _randomMove() {
        // 获取目标点
        this._getTargetPosCount = 0;
        let targtPos = this._getTargetPos();

        let action = cc.sequence(
            cc.moveTo(2, targtPos).easing(cc.easeInOut(2)),
            cc.callFunc(() => {
                this._randomMove();
            })
        )
        this.node.runAction(action);
    },

    _getTargetPos() {
        this._getTargetPosCount++;
        // 获取目标点
        let speed = 100;
        // 获取方向
        let angle = Math.random() * 360;
        var dir = cc.v2(Math.cos(angle), Math.sin(angle));
        //单位化向量
        dir.normalizeSelf();
        let targetPos = cc.v2(this.node.x + dir.x * speed, this.node.y + dir.y * speed);

        // 判断是否可移动
        if (targetPos.x > this.node.parent.width / 2 || targetPos.x < -this.node.parent.width / 2
            || targetPos.y > this.node.parent.height / 2 || targetPos.y < -this.node.parent.height / 2) {
            if (this._getTargetPosCount >= 5) {
                return this.node.position;
            }
            return this._getTargetPos();
        }
        return targetPos
    },

    _onTouchStart() {
        G.ui.openUI('PanelRandomAnimal', { index: this._index, node: this.node });
    },

    onEnable() {
        this.node.on('touchstart', this._onTouchStart, this);
    },

    onDisable() {
        this.node.off('touchstart', this._onTouchStart, this);
    },

    // update (dt) {},
});
